package priv.xp.androidexample.datasource

import androidx.paging.DataSource
import androidx.paging.PageKeyedDataSource
import kotlinx.coroutines.*
import priv.xp.androidexample.model.Girl
import priv.xp.androidexample.repository.GirlRepository

class GirlDataSource(private val girlRepository: GirlRepository) : PageKeyedDataSource<Int, Girl>(), CoroutineScope by MainScope() {
    override fun loadInitial(
        params: LoadInitialParams<Int>,
        callback: LoadInitialCallback<Int, Girl>
    ) {
        launch {
            val girls = girlRepository.awaitLoadPage(1)

            callback.onResult(girls, null, 2)
        }
    }

    override fun loadAfter(params: LoadParams<Int>, callback: LoadCallback<Int, Girl>) {
        launch {
            val page = params.key
            val girls = girlRepository.awaitLoadPage(page)
            callback.onResult(girls, params.key + 1)
        }
    }

    override fun loadBefore(params: LoadParams<Int>, callback: LoadCallback<Int, Girl>) {
        TODO("not implemented") //To change body of created functions use File | Settings | File Templates.
    }

}

class GirlPageDataSourceFactory(private val girlRepository: GirlRepository): DataSource.Factory<Int,Girl>() {
    override fun create(): DataSource<Int, Girl> {
        return GirlDataSource(girlRepository)
    }
}